package com.qd.panda.gas.station;

import cn.hutool.core.exceptions.ExceptionUtil;
import com.cdqidi.constant.ConstantDto;
import com.cdqidi.util.SpringContextHolder;
import com.qd.common.panda.constant.PandaConstant;
import com.qd.common.panda.domain.entity.stroke.UserStrokeOrderDTO;
import com.qd.common.panda.domain.entity.stroke.preferential.UserStrokeOrderPreferentialLogDTO;
import com.qd.common.panda.domain.enums.GasStationCompanyNameEnum;
import com.qd.common.panda.event.GasEvent;
import com.qd.common.sys.domain.entity.log.SendLogDTO;
import com.qd.common.sys.event.SendLogEvent;
import com.qd.panda.gas.station.base.GasHttpServiceInitApplicationContextAware;
import com.qd.panda.gas.station.req.PayNotifyReqDTO;
import com.qd.panda.service.stroke.order.GasOrderService;
import com.qd.panda.service.stroke.order.UserStrokeOrderPreferentialLogService;
import com.qd.panda.service.stroke.order.UserStrokeOrderService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.event.EventListener;
import org.springframework.http.HttpMethod;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.time.LocalDateTime;
import java.util.List;

/**
 * 加油信息处理
 *
 * @author sjk
 * @create 2022-10-12 10:02
 * @since 1.0.0
 */
@Service
@RequiredArgsConstructor
@Slf4j
public class GasSyncService {
    private final GasOrderService gasOrderService;
    private final UserStrokeOrderPreferentialLogService userStrokeOrderPreferentialLogService;
    private final UserStrokeOrderService userStrokeOrderService;

    @Async
    @EventListener(classes = GasEvent.class)
    @Transactional(rollbackFor = Exception.class)
    public void doNotify(GasEvent gasEvent) {
        long start = System.currentTimeMillis();
        String orderId = (String) gasEvent.getSource();
        SendLogDTO sendLog = new SendLogDTO();
        sendLog.setBid(orderId)
                .setSendState(ConstantDto.SF1)
                .setAddTime(LocalDateTime.now())
                .setLogType(PandaConstant.LOG_TYPE_GAS_PAY_NOTIFY)
                .setReqMethod(HttpMethod.GET.name());
        try {
            try {
                final PayNotifyReqDTO payNotifyReqDTO = gasOrderService.getGasPayNotifyReqDTO(orderId);
                if (null == payNotifyReqDTO) {
                    log.info("支付成功，回调加油站接口失败,orderId： {}", orderId);
                } else {
                    log.info("支付成功，回调加油站接口,加油站所属公司:{},orderId： {},payNotifyReqDTO: {}", payNotifyReqDTO.getGasStationCompanyId(), orderId, payNotifyReqDTO);
                    payNotifyReqDTO.setSendLog(sendLog);
                    GasHttpServiceInitApplicationContextAware.getGasHttpService(payNotifyReqDTO.getGasStationCompanyId()).payNotify(payNotifyReqDTO);
                    if (!payNotifyReqDTO.getGasStationCompanyId().equals(GasStationCompanyNameEnum.E_JIA_YOU.getCode())) {
                        update(orderId, payNotifyReqDTO.getData());
                    }
                    gasOrderService.deleteRedis(orderId);
                    payNotifyReqDTO.freeData();
                }
            } catch (Exception e) {
                final String message = ExceptionUtil.getMessage(e);
                log.info("支付成功，回调加油站接口失败,orderId： {},error: {}", orderId, message);
                sendLog.setErrMsg(message);
                sendLog.setSendState(ConstantDto.SF0);
            }
        } finally {
            long end = System.currentTimeMillis();
            sendLog.setTimeConsumer(end - start);
            SpringContextHolder.publishEvent(new SendLogEvent(sendLog));
        }
    }

    public void update(String orderId, String thirdPartyOrderId) {
        List<UserStrokeOrderPreferentialLogDTO> list = userStrokeOrderPreferentialLogService.getCategoryListByOrderId(orderId);
        if (!list.isEmpty()) {
            for (UserStrokeOrderPreferentialLogDTO userStrokeOrderPreferentialLogDTO : list) {
                if (null == userStrokeOrderPreferentialLogDTO.getThirdPartyOrderId() || !thirdPartyOrderId.equals(userStrokeOrderPreferentialLogDTO.getThirdPartyOrderId())) {
                    userStrokeOrderPreferentialLogDTO.setThirdPartyOrderId(thirdPartyOrderId);
                    userStrokeOrderPreferentialLogService.update(userStrokeOrderPreferentialLogDTO);
                    userStrokeOrderPreferentialLogDTO.freeData();
                }
            }
            list.clear();
        }
        UserStrokeOrderDTO userStrokeOrderDTO = userStrokeOrderService.getByIdDto(orderId);
        if(null !=userStrokeOrderDTO){
            if(!StringUtils.hasLength(userStrokeOrderDTO.getThirdPartyOrderId())){
                userStrokeOrderDTO.setThirdPartyOrderId(thirdPartyOrderId);
                userStrokeOrderService.update(userStrokeOrderDTO);
            }
            userStrokeOrderDTO.freeData();
        }
    }
}